package com.nowcoder;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class SpringTask {
    // 普通线程池
    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    ThreadPoolTaskScheduler taskScheduler;

    static final Logger logger = LoggerFactory.getLogger(SpringTask.class);
    // 普通线程池

    void sleep(Long m) throws InterruptedException {
        Thread.sleep(m);
    }


    // 相比与JDK线程池更加灵活，参数更多
    @Test
    void test1() throws InterruptedException {
        Runnable task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                logger.error("Hello Task");
                sleep(1000L);
            }
        };
        for (int i = 0; i < 10; i++) {
            taskExecutor.submit(task);
        }
        sleep(30000L);
    }

    @Test
    void test2() throws InterruptedException {
        Runnable task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                logger.error("Hello Task");
            }
        };
        // 默认是毫秒
        Date start = new Date(System.currentTimeMillis() + 10000);
        taskScheduler.scheduleAtFixedRate(task, start, 1000);
        sleep(30000L);
    }

    @Async
    void exec1() {
        logger.error("------");
    }

    @Test
    void test_exec1() throws InterruptedException {
        exec1();
        sleep(10000L);
    }

    @Scheduled(initialDelay = 10000, fixedDelay = 1000)
    void exec2() {
        logger.error("haha");
    }

    @Test
    void test_exec2() throws InterruptedException {
        sleep(100000L);
    }

}
